package com.wordcount;

import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.io.IntWritable;
import org.apache.hadoop.io.Text;
import org.apache.hadoop.io.compress.BZip2Codec;
import org.apache.hadoop.io.compress.CompressionCodec;
import org.apache.hadoop.mapreduce.Job;
import org.apache.hadoop.mapreduce.lib.input.CombineFileInputFormat;
import org.apache.hadoop.mapreduce.lib.input.FileInputFormat;
import org.apache.hadoop.mapreduce.lib.output.FileOutputFormat;

import java.io.IOException;

public class WordCountDriver {

    public static void main(String[] args) throws IOException, ClassNotFoundException, InterruptedException {

        // 获取配置信息和job对象
        Configuration conf = new Configuration();
        // 配置mapper端使用压缩
        conf.setBoolean("mapreduce.map.output.compress", true);
        // 配置压缩方式
        conf.setClass("mapreduce.map.output.compress.codec", BZip2Codec.class, CompressionCodec.class);

        Job job = Job.getInstance(conf);

        // 关联本Driver的jar
        job.setJarByClass(WordCountDriver.class);

        // 关联mapper和reducer
        job.setMapperClass(WordCountMapper.class);
        job.setReducerClass(WordCountReducer.class);

        // 可以设置Combiner，减轻Reducer需要处理的数据，但是要保证不能更改Mapper输出的数据
        job.setCombinerClass(WordCountReducer.class);

        // 设置mapper输出的kv
        job.setMapOutputKeyClass(Text.class);
        job.setMapOutputValueClass(IntWritable.class);

        // 设置最终输出的kv
        job.setOutputKeyClass(Text.class);
        job.setOutputValueClass(IntWritable.class);

        // Reduce开启压缩
        FileOutputFormat.setCompressOutput(job, true);

        // 设置压缩方式
        FileOutputFormat.setOutputCompressorClass(job, BZip2Codec.class);

        // 设置输入和输出路径
        FileInputFormat.setInputPaths(job, new Path(args[0]));
        FileOutputFormat.setOutputPath(job, new Path(args[1]));

        // 应对小文件，可以使用CombineTextInputFormat
        job.setInputFormatClass(CombineFileInputFormat.class);
        // 设置切片的大小
        CombineFileInputFormat.setMaxInputSplitSize(job, 4194304);

        // 提交job
        boolean result = job.waitForCompletion(true);
        System.exit(result ? 0 : 1);
    }
}
